<template>
  <div class="fixed right-0 top-0 h-full z-40 bg-[#282a36] border-l border-[#44475a] flex flex-col" :style="{ width: panelWidth + 'px' }">
    <!-- 拖拽分割线 -->
    <div 
      class="absolute left-0 top-0 w-1 h-full bg-[#44475a] hover:bg-[#bd93f9] cursor-col-resize transition-colors group"
      @mousedown="startResize"
      :title="`调整宽度 (300px - ${getMaxWidth()}px)`"
    >
      <!-- 宽度提示 -->
      <div class="absolute left-2 top-1/2 transform -translate-y-1/2 bg-[#282a36] text-[#f8f8f2] text-xs px-2 py-1 rounded opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none whitespace-nowrap border border-[#44475a]">
        {{ panelWidth }}px
      </div>
    </div>
    
    <!-- 面板头部 -->
    <div class="flex items-center justify-between px-4 py-3 border-b border-[#44475a] bg-[#21222c]">
      <div class="flex items-center space-x-3">
        <div class="w-7 h-7 bg-gradient-to-br from-[#ff79c6] to-[#bd93f9] rounded-lg flex items-center justify-center shadow-sm">
          <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
          </svg>
        </div>
        <div>
          <h3 class="text-sm font-semibold text-[#f8f8f2]">AI助手</h3>
          <p class="text-xs text-[#6272a4]">智能编程伙伴</p>
        </div>
      </div>
      <button 
        @click="closePanel"
        class="p-2 hover:bg-[#44475a] rounded-lg transition-colors group"
      >
        <svg class="w-4 h-4 text-[#6272a4] group-hover:text-[#f8f8f2] transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
        </svg>
      </button>
    </div>

    <!-- 模型选择 -->
    <div class="px-4 py-3 border-b border-[#44475a]">
      <div class="space-y-2">
        <label class="text-xs font-medium text-[#6272a4] uppercase tracking-wide">AI模型</label>
        <select 
          v-model="selectedModel"
          class="w-full px-3 py-2 bg-[#21222c] border border-[#44475a] rounded-lg text-sm text-[#f8f8f2] focus:ring-2 focus:ring-[#bd93f9] focus:border-[#bd93f9] transition-all"
        >
          <option v-for="model in AI_MODELS" :key="model.value" :value="model.value">
            {{ model.label }}
          </option>
        </select>
      </div>
    </div>

    <!-- 会话管理 -->
    <div class="px-4 py-3 border-b border-[#44475a]">
      <button 
        @click="startNewSession"
        class="w-full px-4 py-2.5 bg-gradient-to-r from-[#50fa7b] to-[#8be9fd] text-[#282a36] rounded-lg text-sm font-medium transition-all hover:shadow-lg hover:scale-[1.02]"
      >
        <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
        </svg>
        开始新对话
      </button>
    </div>

    <!-- 会话历史 -->
    <div v-if="sessions.length > 0" class="flex-1 overflow-y-auto">
      <div class="px-4 py-2">
        <h4 class="text-xs font-medium text-[#6272a4] uppercase tracking-wide mb-2">对话历史</h4>
      </div>
      <div class="px-2 space-y-1">
        <div 
          v-for="session in sessions" 
          :key="session.id"
          @click="loadSession(session.id)"
          :class="[
            'px-3 py-2 rounded-lg cursor-pointer text-sm transition-all duration-200 flex items-center justify-between group',
            currentSessionId === session.id 
              ? 'bg-[#bd93f9] text-[#282a36] shadow-sm' 
              : 'text-[#f8f8f2] hover:bg-[#44475a]'
          ]"
        >
          <span class="truncate font-medium">{{ session.title }}</span>
          <button 
            @click.stop="deleteSession(session.id)"
            class="ml-2 p-1 hover:bg-[#ff5555] rounded opacity-0 group-hover:opacity-100 transition-all"
          >
            <svg class="w-3 h-3 text-current" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
            </svg>
          </button>
        </div>
      </div>
    </div>

    <!-- 消息区域 -->
    <div v-if="currentSessionId" class="flex-1 overflow-y-auto px-4 py-4">
      <div class="space-y-4">
        <div 
          v-for="message in messages" 
          :key="message.id"
          :class="[
            'flex',
            message.role === 'user' ? 'justify-end' : 'justify-start'
          ]"
        >
          <div 
            :class="[
              'max-w-[85%] px-4 py-3 rounded-xl text-sm shadow-sm',
              message.role === 'user' 
                ? 'bg-gradient-to-r from-[#bd93f9] to-[#ff79c6] text-[#282a36]' 
                : 'bg-[#21222c] text-[#f8f8f2] border border-[#44475a]'
            ]"
          >
            <p class="whitespace-pre-wrap leading-relaxed">{{ message.content }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="p-4 border-t border-[#44475a] bg-[#21222c]">
      <div class="flex space-x-3">
        <div class="flex-1 relative">
          <input
            v-model="inputMessage"
            @keydown.enter="sendMessage"
            type="text"
            placeholder="输入消息..."
            class="w-full px-4 py-3 bg-[#282a36] border border-[#44475a] rounded-xl text-sm text-[#f8f8f2] placeholder-[#6272a4] focus:ring-2 focus:ring-[#bd93f9] focus:border-[#bd93f9] transition-all"
            :disabled="isLoading"
          />
        </div>
        <button 
          @click="sendMessage"
          :disabled="!inputMessage.trim() || isLoading"
          class="px-4 py-3 bg-gradient-to-r from-[#50fa7b] to-[#8be9fd] hover:from-[#4ade80] hover:to-[#7dd3fc] disabled:opacity-50 disabled:cursor-not-allowed text-[#282a36] rounded-xl text-sm font-medium transition-all shadow-lg hover:shadow-xl transform hover:scale-105 disabled:transform-none"
        >
          <svg v-if="isLoading" class="w-5 h-5 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
          </svg>
          <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path>
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { aiApi, type AIChatSession, type AIChatMessage, AI_MODELS } from '@/api/ai'

interface Props {
  questionId?: number
  sessionType?: string
}

const props = withDefaults(defineProps<Props>(), {
  sessionType: 'question'
})

const emit = defineEmits<{
  close: []
  widthChange: [width: number]
}>()

// 响应式数据
const selectedModel = ref('gpt-3.5-turbo')
const inputMessage = ref('')
const isLoading = ref(false)
const sessions = ref<AIChatSession[]>([])
const messages = ref<AIChatMessage[]>([])
const currentSessionId = ref<number | null>(null)
// 计算最大允许宽度
const getMaxWidth = () => {
  return Math.min(800, window.innerWidth / 4)
}

// 计算初始宽度，确保不超过限制
const getInitialWidth = () => {
  const maxWidth = getMaxWidth()
  return Math.min(400, maxWidth)
}

const panelWidth = ref(getInitialWidth())
const isResizing = ref(false)

// 计算属性
const getCurrentModelDescription = () => {
  const model = AI_MODELS.find(m => m.value === selectedModel.value)
  return model?.description || ''
}

// 方法
const closePanel = () => {
  emit('close')
}

const startNewSession = () => {
  currentSessionId.value = null
  messages.value = []
  inputMessage.value = ''
}

const loadSession = async (sessionId: number) => {
  currentSessionId.value = sessionId
  try {
    const response = await aiApi.getChatMessages(sessionId)
    messages.value = response.data?.messages || []
  } catch (error) {
    console.error('加载会话消息失败:', error)
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const message = inputMessage.value.trim()
  inputMessage.value = ''
  isLoading.value = true

  try {
    const response = await aiApi.sendMessage({
      message,
      model: selectedModel.value,
      session_id: currentSessionId.value || undefined,
      question_id: props.questionId,
      session_type: props.sessionType
    })

    // 更新会话ID
    if (!currentSessionId.value) {
      currentSessionId.value = response.data?.session_id || null
    }

    // 添加用户消息
    messages.value.push({
      id: Date.now(),
      session_id: response.data?.session_id || 0,
      role: 'user',
      content: message,
      model: selectedModel.value,
      tokens: 0,
      created_at: new Date().toISOString()
    })

    // 添加AI回复
    messages.value.push({
      id: Date.now() + 1,
      session_id: response.data?.session_id || 0,
      role: 'assistant',
      content: response.data?.message || '',
      model: response.data?.model || selectedModel.value,
      tokens: response.data?.tokens || 0,
      created_at: new Date().toISOString()
    })

    // 刷新会话列表
    await loadSessions()
  } catch (error) {
    console.error('发送消息失败:', error)
  } finally {
    isLoading.value = false
  }
}

const deleteSession = async (sessionId: number) => {
  try {
    await aiApi.deleteChatSession(sessionId)
    await loadSessions()
    
    if (currentSessionId.value === sessionId) {
      startNewSession()
    }
  } catch (error) {
    console.error('删除会话失败:', error)
  }
}

const loadSessions = async () => {
  try {
    const response = await aiApi.getChatSessions()
    sessions.value = response.data?.sessions || []
  } catch (error) {
    console.error('加载会话列表失败:', error)
  }
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 1000 * 60) {
    return '刚刚'
  } else if (diff < 1000 * 60 * 60) {
    return `${Math.floor(diff / (1000 * 60))}分钟前`
  } else if (diff < 1000 * 60 * 60 * 24) {
    return `${Math.floor(diff / (1000 * 60 * 60))}小时前`
  } else {
    return date.toLocaleDateString()
  }
}

// 拖拽调整大小
const startResize = (e: MouseEvent) => {
  isResizing.value = true
  const startX = e.clientX
  const startWidth = panelWidth.value

  const handleMouseMove = (e: MouseEvent) => {
    const deltaX = startX - e.clientX
    const newWidth = startWidth + deltaX
    
    // 计算最大宽度限制（屏幕宽度的1/4）
    const maxWidth = getMaxWidth()
    const clampedWidth = Math.max(300, Math.min(maxWidth, newWidth))
    
    panelWidth.value = clampedWidth
    emit('widthChange', clampedWidth)
  }

  const handleMouseUp = () => {
    isResizing.value = false
    document.removeEventListener('mousemove', handleMouseMove)
    document.removeEventListener('mouseup', handleMouseUp)
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 窗口大小变化处理
const handleWindowResize = () => {
  const maxWidth = getMaxWidth()
  if (panelWidth.value > maxWidth) {
    panelWidth.value = maxWidth
    emit('widthChange', maxWidth)
  }
}

// 生命周期
onMounted(() => {
  loadSessions()
  // 初始化时发出宽度变化事件
  emit('widthChange', panelWidth.value)
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleWindowResize)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', handleWindowResize)
})
</script>
